<template>
  <div class="mainbox">
    <div class="content">
      <div class="exit">
        <van-icon size="20" name="cross" @click="close" />
      </div>
      <div class="fword">欢迎登录暖暖房屋</div>
      <!-- <img src="@/assets/phone.png" alt="" width="11px" height="18px" class="phone"> -->
      <div class="loginpart">
        <img src="@/assets/logo.png" alt="" />
        <div class="sword">有温度的房屋在线交易平台</div>
        <van-form @submit="onSubmit">
          <van-field
            v-model="tel"
            type="tel"
            name="手机号"
            maxlength="11"
            placeholder="请输入手机号"
            :rules="[{ required: true }]"
            class="input"
          />
          <van-field
            v-model="code"
            type="number"
            name="验证码"
            maxlength="5"
            placeholder="请输入验证码"
            :rules="[{ required: true }]"
          />
          <span v-show="showgetcode" class="yan" @click="getcode">
            获取验证码
          </span>
          <span v-show="!showgetcode" class="yan">{{ time }}S</span>
          <div class="other">
            <van-checkbox v-model="checked" checked-color="#45b7cb" />
            <div>
              登录即代表您已阅读并同意暖暖房屋
              <span @click="touse">用户使用协议</span>、
              <span @click="topre">隐私保护政策</span>
            </div>
          </div>
          <van-button ref="loginbtn" disabled native-type="submit">
            登录
          </van-button>
        </van-form>
      </div>
    </div>
  </div>
</template>

<script>
import { getDXcode } from "../apis/login";
import { _local } from "@/utils/storage";
import local from "../utils/local";
import { addLog } from "@/apis/user";

export default {
  data() {
    return {
      tel: "",
      code: "",
      showgetcode: true,
      time: 60,
      checked: false,
      timer: "",
    };
  },
  created() {
    // if (local.get('tel')) {
    //   this.tel = local.get('tel')
    // }
    // if (local.get('code')) {
    //   this.code = local.get('code')
    // }
  },
  beforeUpdate() {
    this.change();
  },
  destroyed() {
    clearInterval(this.timer);
  },
  methods: {
    close() {
      this.$router.go(-1);
    },
    touse() {
      local.set("tel", this.tel);
      local.set("code", this.code);
      this.$router.push({ path: "/serve" });
    },
    topre() {
      local.set("tel", this.tel);
      local.set("code", this.code);
      this.$router.push({ path: "/privacy" });
    },
    connectWebsocket(res) {
      const _this = this;
      if ("WebSocket" in window) {
        console.log("您的浏览器支持 WebSocket!");
        const ws = new WebSocket("ws://47.92.222.96:7272");
        _this.$global.setWs(ws);
        ws.onopen = function (e) {
          console.log("开始连接");
          let login_data = {
            type: "login",
            client_name: res.result.realname,
            room_id: "",
          };
          login_data = JSON.stringify(login_data);
          ws.send(login_data);
        };
        ws.onmessage = function (e) {
          console.log(JSON.stringify(e.data));
          let msg = JSON.parse(e.data);
          if (msg.type == "login") {
            fetch(`${_this.$imUrl}/im/bind`, {
              method: "POST",
              headers: {
                "Content-type":
                  "application/x-www-form-urlencoded; charset=UTF-8",
                token: res.result.im_token,
              },
              body: `client_id=${msg.client_id}`,
            })
              .then((res) => res.json())
              .then((res) => {
                console.log("绑定", res);
                _this.$store.dispatch("im/setUnReadCount", {
                  unReadCount:
                    _local.get("unReadCount") || res.data.no_read_all,
                });
              });
          } else if (msg.type == "say") {
            _local.set("unReadCount", msg.no_read_all);
            _this.$store.dispatch("im/setUnReadCount", {
              unReadCount: msg.no_read_all,
            });
          }
        };
        ws.onclose = function (e) {
          console.log("连接中断");
          _this.connectWebsocket();
        };
      } else {
        console.log("您的浏览器不支持 WebSocket!");
      }
    },
    onSubmit() {
      const _this = this;
      if (this.checked) {
        _this.$store
          .dispatch("manage/register", {
            mobile: this.tel,
            verifyCode: this.code,
            city_name: _local.get("city"),
          })
          .then((response) => {
            console.log("登录信息", response);
            _this.connectWebsocket(response);
            const code = response.code;
            const userId = response.result.userId;
            const ryId = response.result.ryId;
            const imUser = {};
            imUser.imId = response.result.im_id;
            imUser.imToken = response.result.im_token;
            _local.set("imUser", JSON.stringify(imUser));
            _local.set("ryId", ryId);
            _local.set("token", response.result.token);
            if (code === 2007) {
              _this.$toast("验证码错误");
              return;
            }

            if (code === 2006) {
              _this.$toast("验证码过期");
              return;
            }

            if (code === 201) {
              local.del("tel");
              local.del("code");
              _this.$store
                .dispatch("manage/getInfo", { userId: userId })
                .then((res) => {
                  console.log("用户信息", res);
                  _local.set("user", JSON.stringify(res));
                  addLog({
                    adcode: _local.get("adCode"),
                    code: "holding",
                    page_name: "登录页",
                    system: _local.get("device"),
                    uid: ryId,
                    time: this.time,
                    describe: `城市:${_local.get("city")}`,
                  }).then((res) => {
                    console.log("addLog", JSON.stringify(res));
                  });
                  if (
                    res.result.role === 1 ||
                    res.result.role === 2 ||
                    res.result.role === 3 ||
                    res.result.role === 4 ||
                    res.result.role === 5
                  ) {
                    // _this.$router.push({ path: "/home/me" });
                    _this.$router.go(-1);
                  } else if (res.result.role === 0) {
                    _this.$router.push({ path: "/rolechoose" });
                  }
                });
            }
          });
      } else {
        this.$toast("请阅读并勾选下方协议");
      }
    },

    change() {
      if (this.tel.length === 11 && this.code.length === 5 && this.checked) {
        this.$refs.loginbtn.disabled = false;
        this.$refs.loginbtn.style = "background-color:#45b7cb;color:#fff";
      } else {
        this.$refs.loginbtn.style = "";
        this.$refs.loginbtn.disabled = true;
      }
    },
    async getcode() {
      if (this.tel.length === 11) {
        this.showgetcode = false;
        this.count60();
        await getDXcode({
          type: 1,
          mobile: this.tel,
        }).then((response) => {
          if (response.code === 200) {
            this.$toast.success("发送成功");
          }
        });
      } else {
        this.$toast("请输入正确的电话");
      }
    },
    count60() {
      const _this = this;
      const timer = setInterval(function () {
        _this.time--;
        if (_this.time <= 0) {
          _this.showgetcode = true;
          _this.time = 60;
          clearInterval(timer);
        }
      }, 1000);
    },
  },
};
</script>

<style lang="less" scoped>
// .phone{
//   position: absolute;
//   left: 20px;
//   bottom: 270px;
//   z-index: 100;
// }
.fword {
  font-size: 20px;
  font-weight: bold;
  margin-top: 25px;
}
.mainbox {
  height: 100%;
  // background: url("~@/assets/loginbi.png") no-repeat;
  // background-size: 100% 100%;
  .content {
    margin: 0 15px;
    height: 520px;
    .exit {
      height: 100px;
      box-sizing: border-box;
      padding-top: 60px;
      padding-left: 10px;
    }
    .loginpart {
      position: relative;
      height: 520px;
      background-color: #fff;
      border-radius: 10px;
      text-align: center;
      img {
        margin-top: 100px;
        height: 55px;
        width: 59px;
      }
      .sword {
        font-size: 14px;
        margin-top: 15px;
      }
      /deep/.van-field {
        box-sizing: border-box;
        padding: 20px 0;
        margin: 0 10px;
        border: none;
        border-bottom: 1px solid #ddd;
        display: block;
        width: 94%;
        margin-top: 20px;
        input {
          text-indent: 1em;
          font-size: 15px;
        }
        .van-field__error-message {
          position: relative;
        }
      }
      .yan {
        position: absolute;
        right: 25px;
        bottom: 185px;
        color: #333;
      }
      .van-button {
        width: 85%;
        border-radius: 25px;
        height: 50px;
        background-color: #eee;
        border: none;
        color: #999;
        font-weight: bold;
        letter-spacing: 5px;
        margin-top: 10px;
      }
      /deep/.van-button--disabled {
        opacity: 1;
      }
      .other {
        margin: 25px 15px 0;
        display: flex;
        justify-content: center;
        padding-bottom: 10px;
        font-size: 12px;
        color: #666;
        text-align: left;
        .van-checkbox {
          width: 40px;
        }
        > div {
          span {
            font-weight: bold;
            color: #333;
          }
        }
      }
    }
  }
}
input::-webkit-input-placeholder {
  color: #999;
}
input::-moz-placeholder {
  color: #999;
}
input:-moz-placeholder {
  color: #999;
}
input:-ms-input-placeholder {
  color: #999;
}
</style>
